package com.yunyi.camunda.config;

import com.yunyi.camunda.common.exception.YunyiException;
import com.yunyi.camunda.pojo.Result;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Objects;

/**
 * 统一拦截数据处理
 */
@RestControllerAdvice
public class ResultHandler implements ResponseBodyAdvice<Object> {
    /**
     * 判断是否进行拦截处理
     *
     * @param methodParameter 方法参数
     * @param aClass          class文件
     * @return 拦截Boolean
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        Class excludeClass = Objects.requireNonNull(methodParameter.getMethod()).getDeclaringClass();
        if (YunyiException.class.getTypeName().equals(excludeClass.getTypeName())) {
            return false;
        }
        return true;

    }

    /**
     * 实际拦截处理方法
     *
     * @param o                  返回相关的处理
     * @param methodParameter    方法
     * @param mediaType          mediaType
     * @param aClass             aClass
     * @param serverHttpRequest  request
     * @param serverHttpResponse response
     * @return 返回数据
     */
    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        String msg = o.toString();
        return Result.failMessage(msg);
    }
}
